package org.ggn.dao;

import org.ggn.exception.GradeException;
import org.ggn.model.Grade;
import org.ggn.util.HibernateUtil;
import org.hibernate.Session;

public class GradeDao implements GDao {

	@Override
	public void add(Grade c) {
		Session session = null;
		try {
			session = HibernateUtil.openSession();
			session.beginTransaction();

			if(c.getName()==null){
				throw new GradeException("课程不能为空");
			}
			Grade u = (Grade) session.createQuery("select us from Grade us where name like ?")
					.setParameter(0,c.getName()).uniqueResult();
			if(u!=null){
				throw new GradeException("课程已存在");
			}
			session.save(c);
			
			session.getTransaction().commit();
		} 
		finally{
			HibernateUtil.close(session);
		}
	}

	@Override
	public void delete(Grade c) {
		Session session = null;
		try {
			session = HibernateUtil.openSession();
			session.beginTransaction();
			
			session.delete(c);
			
			session.getTransaction().commit();
		} catch (Exception e) {
			e.printStackTrace();
			if(session!=null){
				session.getTransaction().rollback();
			}
		}finally{
			HibernateUtil.close(session);
		}
	}

	@Override
	public void update(Grade c) {
		Session session = null;
		try {
			session = HibernateUtil.openSession();
			session.beginTransaction();
			Grade u = (Grade)session.load(Grade.class, c.getId());
			if(u==null){
				throw new GradeException("更新的课程不存在");
			}
			u.setName(c.getName());
			u.setType(c.getType());
			u.setCourses(c.getCourses());
			session.update(u);
			
			session.getTransaction().commit();
		} finally{
			HibernateUtil.close(session);
		}
	}

	@Override
	public Grade load(int id) {
		Session session = null;
		Grade u = null;
		try {
			session = HibernateUtil.openSession();
			if(id==0){
				throw new GradeException("查找不存在");
			}
			u = (Grade)session.get(Grade.class, id);//load(Grade.class, id);
			return u;
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			HibernateUtil.close(session);
		}
		return u;
	
	}

}
